package com.xbongbong.paas.print.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.esign.exception.DefineException;
import com.xbongbong.esign.helper.FileTemplateHelper;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.pojo.dto.FormGetDTO;
import com.xbongbong.paas.print.helper.OssHelper;
import com.xbongbong.paas.print.pojo.dto.PaasPrintAddDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintEditDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDataByProcessDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDataDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDatasByProcessDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDatasDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDefaultDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintListDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintManageListDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintNameEditDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintTemplateSortDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintUpdateDTO;
import com.xbongbong.paas.print.pojo.dto.SubFormAttrDataDTO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintEditVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintListVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintManageListVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintNameEditVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintSaveVO;
import com.xbongbong.paas.print.pojo.vo.PrintDisplayAttrVO;
import com.xbongbong.paas.print.pojo.vo.SubFormAttrDataVO;
import com.xbongbong.paas.print.service.PaasPrintService;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.util.Wkhtmltopdf;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.Html2pdfForEsignVO;
import com.xbongbong.paas.toolbox.wrap.PdfParamDTO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.esign.pojo.vo.EsignFileUploadVO;
import com.xbongbong.pro.print.pojo.pojo.vo.PrintMobileVO;
import com.xbongbong.pro.process.pojo.dto.ProcessFormFilterDTO;
import com.xbongbong.pro.process.pojo.vo.ProcessFormFilterVO;
import com.xbongbong.pro.template.pojo.dto.TemplateDTO;
import com.xbongbong.pro.template.pojo.vo.EnableVO;
import com.xbongbong.saas.domain.entity.EsignTaskEntity;
import com.xbongbong.saas.enums.EsignTaskTypeEnum;
import com.xbongbong.saas.model.EsignTaskModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Objects;

/**
 * 创建时间： 2018/9/11 10:12
 * 修改时间： 2018/9/11 10:12 梁鲁江
 *
 * @author 梁鲁江
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/print")
public class PaasPrintController {
    @Resource
    private PaasPrintService paasPrintService;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private FileTemplateHelper fileTemplateHelper;
    @Resource
    private EsignTaskModel esignTaskModel;
    @Resource
    private OssHelper ossHelper;


    private static final Logger LOG = LoggerFactory.getLogger(PaasPrintController.class);

    /**
     * 获取系统默认模板
     * @param paasPrintGetDefaultDTO 入参
     * @param br 校验结果
     */
    @RequestMapping(value = "/getDefaultTemplate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getDefaultTemplate(@RequestBody @Valid PaasPrintGetDefaultDTO paasPrintGetDefaultDTO, BindingResult br){
        XbbResponse<PaasPrintEditVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasPrintEditVO paasPrintEditVO = paasPrintService.getDefaultPrintTemplate(paasPrintGetDefaultDTO);
                response = new XbbResponse<>(paasPrintEditVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 新建打印模板
     * @param paasPrintAddDTO 前端入参
     * @param br 校验结果
     * @return 返回
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String add(@RequestBody @Valid PaasPrintAddDTO paasPrintAddDTO, BindingResult br) {
        XbbResponse<PaasPrintSaveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasPrintSaveVO paasPrintSaveVO = paasPrintService.addPaasPrintTemplate(paasPrintAddDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String update(@RequestBody @Valid PaasPrintUpdateDTO paasPrintUpdateDTO, BindingResult br) {
        XbbResponse<PaasPrintSaveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasPrintSaveVO paasPrintSaveVO = paasPrintService.updatePaasPrintTemplate(paasPrintUpdateDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String edit(@RequestBody @Valid PaasPrintEditDTO paasPrintEditDTO, BindingResult br) {
        XbbResponse<PaasPrintEditVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasPrintEditVO paasPrintEditVO = paasPrintService.editPaasPrintTemplate(paasPrintEditDTO);
                response = new XbbResponse<>(paasPrintEditVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取基本信息列表
     * @param paasPrintListDTO 前端入参
     * @param br 校验结果
     * @return 返回
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String list(@RequestBody @Valid PaasPrintListDTO paasPrintListDTO, BindingResult br) {
        XbbResponse<PaasPrintListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasPrintListVO paasPrintListVO = paasPrintService.list(paasPrintListDTO);
                response = new XbbResponse<>(paasPrintListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 打印管理列表
     * @param paasPrintManageListDTO 入参
     * @param br br
     * @return 结果
     */
    @RequestMapping(value = "/manageList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String manageList(@RequestBody @Valid PaasPrintManageListDTO paasPrintManageListDTO, BindingResult br) {
        XbbResponse<PaasPrintManageListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasPrintManageListVO paasPrintManageListVO = paasPrintService.manageList(paasPrintManageListDTO);
                response = new XbbResponse<>(paasPrintManageListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 获取可打印的字段
     * @param formGetDTO 前端入参
     * @param br 返回
     * @return 返回
     */
    @RequestMapping(value = "/disPlayAttr", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String disPlayAttr(@RequestBody @Valid FormGetDTO formGetDTO, BindingResult br) {
        XbbResponse<PrintDisplayAttrVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PrintDisplayAttrVO printDisplayAttrVO = paasPrintService.getDisPlayAttr(formGetDTO);
                response = new XbbResponse<>(printDisplayAttrVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取子表单的数据
     * @param subFormAttrDataDTO 入参
     * @param br 校验
     * @return 结果
     */
    @RequestMapping(value = "/getSubFormAttrData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getSubFormAttrData(@RequestBody @Valid SubFormAttrDataDTO subFormAttrDataDTO, BindingResult br) {
        XbbResponse<SubFormAttrDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                SubFormAttrDataVO subFormAttrDataVO = paasPrintService.getSubFormAttrData(subFormAttrDataDTO);
                response = new XbbResponse<>(subFormAttrDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 删除打印模板
     * @param paasPrintEditDTO 入参
     * @param br br
     * @return String
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delete(@RequestBody @Valid PaasPrintEditDTO paasPrintEditDTO, BindingResult br) {
        XbbResponse<PaasPrintSaveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasPrintSaveVO paasPrintSaveVO = paasPrintService.delete(paasPrintEditDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 复制打印模板
     * @param paasPrintEditDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/copy", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String copy(@RequestBody @Valid PaasPrintEditDTO paasPrintEditDTO, BindingResult br) {
        XbbResponse<PaasPrintSaveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(paasPrintEditDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(paasPrintEditDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                PaasPrintSaveVO paasPrintSaveVO = paasPrintService.copy(paasPrintEditDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取表单模板列表
     * @param templateDTO 入参
     * @param br br
     * @return String
     */
    @RequestMapping(value = "/enableFormList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String enableFormList(@RequestBody @Valid TemplateDTO templateDTO, BindingResult br) {
        XbbResponse<EnableVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            EnableVO enableVO = paasPrintService.enableFormList(templateDTO);
            response = new XbbResponse<>(enableVO);
        }
        return JSON.toJSONString(response);
    }

    /**
     * 打印获取数据
     * @param paasPrintGetDataDTO 入参
     * @param br br
     * @return String
     */
    @RequestMapping(value = "/getData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getData(@RequestBody @Valid PaasPrintGetDataDTO paasPrintGetDataDTO, BindingResult br) {
        XbbResponse<JSONArray> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                JSONArray vO = paasPrintService.getData(paasPrintGetDataDTO);
                response = new XbbResponse<>(vO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 批量打印获取数据
     * @param paasPrintGetDatasDTO 入参
     * @param br br
     * @return String
     */
    @RequestMapping(value = "/getDatas", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getDatas(@RequestBody @Valid PaasPrintGetDatasDTO paasPrintGetDatasDTO, BindingResult br) {
        XbbResponse<JSONArray> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                JSONArray vO = paasPrintService.getDatas(paasPrintGetDatasDTO);
                response = new XbbResponse<>(vO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 将html转为pdf文件
     * @param request  request
     * @param httpResponse response
     * @return pdf文件
     * @throws IOException IO异常
     */
    @RequestMapping(value = "/convertPdf", method = RequestMethod.POST)
    public String convertPdf(HttpServletRequest request,HttpServletResponse httpResponse) throws IOException {
        // 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 判断是否是多数据段提交格式
        String name = "";
        byte[] bytes = new byte[1024];
        try{
            if (multipartResolver.isMultipart(request)) {
                // pdf生成参数解析
                String src = null;
                HashMap<String,String > nameToFileName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                PdfParamDTO pdfParamDTO = JsonHelperUtil.parseObject(request.getParameter("options"),PdfParamDTO.class);
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iterator = multiRequest.getFileNames();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    MultipartFile multipartFile = multiRequest.getFile(next);
                    if (multipartFile == null) {
                        continue;
                    }
                    String fileName = multipartFile.getOriginalFilename();
                    if (fileName == null || "".equals(fileName.trim())) {
                        continue;
                    }
                    // 针对IE环境下filename是整个文件路径的情况而做以下处理
                    int index = fileName.lastIndexOf("\\");
                    String newStr;
                    if (index > -1) {
                        newStr = fileName.substring(index + 1);
                    } else {
                        newStr = fileName;
                    }
                    if (!"".equals(newStr)) {
                        fileName = newStr;
                    }
                    String pathName = Wkhtmltopdf.PRINT_BASE_PATH + fileName;
                    File file = new File(pathName);
                    multipartFile.transferTo(file);
                    if (Objects.equals(next,"file")) {
                        src = pathName;
                    }
                    nameToFileName.put(next,pathName);

                    // html转pdf
                }
                if (nameToFileName.size()>0){
                    bytes = Wkhtmltopdf.html2pdf(src,nameToFileName,pdfParamDTO,null);
                }

            }
        } catch (Exception e){
            LOG.error("打印pdf出错：",e);
            XbbResponse<JSONObject> response = new XbbResponse<>(ErrorCodeEnum.API_FAIL.getCode(), I18nMessageUtil.getMessage(I18nStringConstant.PRINT_ERROR),"");
            return JSON.toJSONString(response);
        }
        // 清空response
        httpResponse.reset();
        // 设置response的Header
        httpResponse.addHeader("Content-Disposition", "attachment;filename="
                + java.net.URLEncoder.encode(name,"utf-8"));
        OutputStream toClient = httpResponse.getOutputStream();
        httpResponse.setContentType("application/pdf;charset=utf-8");
        toClient.write(bytes);
        toClient.flush();
        toClient.close();

        return null;
    }


    /**
     * 移动端支持打印
     * 将html转为pdf文件
     * @param request  request
     * @param httpResponse response
     * @return pdf文件
     * @throws IOException IO异常
     */
    @RequestMapping(value = "/mobile/convertPdf", method = RequestMethod.POST)
    public String convertPdfMobile(HttpServletRequest request,HttpServletResponse httpResponse) throws IOException {
        // 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 判断是否是多数据段提交格式
        String name = "";
        String pathName="";
        String src = null;
        byte[] bytes = new byte[1024];
        try{
            if (multipartResolver.isMultipart(request)) {
                // pdf生成参数解析
                HashMap<String,String > nameToFileName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                PdfParamDTO pdfParamDTO = JsonHelperUtil.parseObject(request.getParameter("options"),PdfParamDTO.class);
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iterator = multiRequest.getFileNames();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    MultipartFile multipartFile = multiRequest.getFile(next);
                    if (multipartFile == null) {
                        continue;
                    }
                    String fileName = multipartFile.getOriginalFilename();
                    if (fileName == null || "".equals(fileName.trim())) {
                        continue;
                    }
                    // 针对IE环境下filename是整个文件路径的情况而做以下处理
                    int index = fileName.lastIndexOf("\\");
                    String newStr;
                    if (index > -1) {
                        newStr = fileName.substring(index + 1);
                    } else {
                        newStr = fileName;
                    }
                    if (!"".equals(newStr)) {
                        fileName = newStr;
                    }
                    pathName = Wkhtmltopdf.PRINT_BASE_PATH + fileName;
                    File file = new File(pathName);
                    multipartFile.transferTo(file);
                    if (Objects.equals(next,"file")) {
                        src = pathName;
                    }
                    nameToFileName.put(next,pathName);

                }
                if (nameToFileName.size()>0){
                    bytes = Wkhtmltopdf.html2pdf(src,nameToFileName,pdfParamDTO, null);
                }
            }
        } catch (Exception e){
            LOG.error("打印pdf出错：",e);
            XbbResponse<JSONObject> response = new XbbResponse<>(ErrorCodeEnum.API_FAIL.getCode(), I18nMessageUtil.getMessage(I18nStringConstant.PRINT_ERROR),"");
            return JSON.toJSONString(response);
        }
//        String url = null;
        XbbResponse<PrintMobileVO> response;
        try {
            String corpid = request.getParameter("corpid");
            // 获取真正的文件名
            String realName = StringUtil.ifEmptyThenDefault(request.getParameter("realName"), "未命名");
            String fileType = "pdf";
            String s = ossHelper.upload2AliyunOss(corpid, bytes, realName, fileType);
            PrintMobileVO printMobileVO = new PrintMobileVO();
            printMobileVO.setUrl(s);
            response = new XbbResponse<>(printMobileVO);
        } catch (Exception e) {
            LOG.error("上传oss出错: ",e);
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100010, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return JSON.toJSONString(response);
    }


    /**
     * 将html转为pdf文件，将文件上传到e签宝
     * @param request  request
     * @param httpResponse response
     * @return pdf文件
     * @throws IOException IO异常
     */
    @RequestMapping(value = "/convertPdfUpload2Esign", method = RequestMethod.POST)
    public String convertPdfUpload2Esign(HttpServletRequest request, HttpServletResponse httpResponse) throws IOException {
        XbbResponse<EsignFileUploadVO> response;
        // 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());

        String name = "";
        String pathName="";
        String src = null;
        byte[] bytes = new byte[1024];
        Html2pdfForEsignVO html2pdfForEsignVO = null;
        try{
            if (multipartResolver.isMultipart(request)) {
                // pdf生成参数解析
                HashMap<String,String > nameToFileName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                PdfParamDTO pdfParamDTO = JsonHelperUtil.parseObject(request.getParameter("options"),PdfParamDTO.class);
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iterator = multiRequest.getFileNames();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    MultipartFile multipartFile = multiRequest.getFile(next);
                    if (multipartFile == null) {
                        continue;
                    }
                    String fileName = multipartFile.getOriginalFilename();
                    if (fileName == null || "".equals(fileName.trim())) {
                        continue;
                    }
                    // 针对IE环境下filename是整个文件路径的情况而做以下处理
                    int index = fileName.lastIndexOf("\\");
                    String newStr;
                    if (index > -1) {
                        newStr = fileName.substring(index + 1);
                    } else {
                        newStr = fileName;
                    }
                    if (!"".equals(newStr)) {
                        fileName = newStr;
                    }
                    pathName = Wkhtmltopdf.PRINT_BASE_PATH + fileName;
                    File file = new File(pathName);
                    multipartFile.transferTo(file);
                    if (Objects.equals(next,"file")) {
                        src = pathName;
                    }
                    nameToFileName.put(next,pathName);
                }
                // html转pdf
                html2pdfForEsignVO = Wkhtmltopdf.html2pdfForEsign(src,pdfParamDTO,nameToFileName);
            }

            String corpid = request.getParameter("corpid");
            Long formId = StringUtil.StringToLong(request.getParameter("formId"), 0L);
            Long dataId = StringUtil.StringToLong(request.getParameter("dataId"), 0L);

            EsignFileUploadVO esignFileUploadVO = getEsignFileUpload(corpid, formId, dataId,
                    html2pdfForEsignVO.getBytes(), html2pdfForEsignVO.getFileName());
            response = new XbbResponse<>(esignFileUploadVO);
        } catch (Exception e){
            LOG.error("打印pdf出错：",e);
            response = new XbbResponse<>(ErrorCodeEnum.API_FAIL.getCode(), I18nMessageUtil.getMessage(I18nStringConstant.PRINT_ERROR),"");
        }

        return JSON.toJSONString(response);
    }

    /**
     * 文件上传
     * @param corpid
     * @param formId
     * @param dataId
     * @param fileBytes
     * @param fileName
     * @return
     * @throws XbbException
     * 创建时间 2020/6/17 1:48 PM
     * 修改时间 2020/6/17 1:48 PM
     * @author chy
     */
    private EsignFileUploadVO getEsignFileUpload(String corpid, Long formId, Long dataId, byte[] fileBytes, String fileName) throws XbbException {
        JSONObject uploadUrlJson = null;
        try {
            uploadUrlJson = fileTemplateHelper.createFileByUpload(corpid, fileBytes, fileName);
        } catch (DefineException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, e.getMessage());
        }
        String fileId = uploadUrlJson.getString("fileId");
        String uploadUrl = uploadUrlJson.getString("uploadUrl");

        JSONObject json = null;
        try {
            json = fileTemplateHelper.streamUpload(fileBytes, uploadUrl);
        } catch (DefineException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, e.getMessage());
        }
        LOG.info("json:" + json);

        EsignFileUploadVO esignFileUploadVO = json.toJavaObject(EsignFileUploadVO.class);

        LOG.info("esignFileUploadVO:" + esignFileUploadVO);

        EsignTaskEntity esignTask = new EsignTaskEntity();
        esignTask.setCorpid(corpid);
        esignTask.setFormId(formId);
        esignTask.setDataId(dataId);
        esignTask.setTaskId(fileId);
        esignTask.setFileName(fileName);
        esignTask.setType(EsignTaskTypeEnum.FILE.getCode());
        esignTaskModel.insert(esignTask);

        return json.toJavaObject(EsignFileUploadVO.class);
    }

    /**
     * 检查模块支不支持打印
     * @param paasPrintListDTO 入参
     * @param br 参数校验
     * @return String
     */
    @RequestMapping(value = "/checkPrintBusiness", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String checkPrintBusiness(@RequestBody @Valid PaasPrintListDTO paasPrintListDTO, BindingResult br) {
        XbbResponse<Boolean> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                Boolean vO = paasPrintService.checkPrintBusiness(paasPrintListDTO);
                response = new XbbResponse<>(vO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 检查表单当前模板数量已达限制
     * @param paasPrintListDTO 入参
     * @param br 参数校验
     * @return String
     */
    @RequestMapping(value = "/checkPrintTemplateNum", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String checkPrintTemplateNum(@RequestBody @Valid PaasPrintListDTO paasPrintListDTO, BindingResult br) {
        XbbResponse<Boolean> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                Boolean vO = paasPrintService.checkPrintTemplateNum(paasPrintListDTO);
                response = new XbbResponse<>(vO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 编辑打印模板名称
     * @param paasPrintNameEditDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updatePrintName", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String update(@RequestBody @Valid PaasPrintNameEditDTO paasPrintNameEditDTO, BindingResult br) throws Exception {
        XbbResponse<PaasPrintNameEditVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasPrintNameEditVO paasPrintNameEditVO = paasPrintService.updatePaasPrintTemplateName(paasPrintNameEditDTO);
                response = new XbbResponse<>(paasPrintNameEditVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 打印模板名称查重(同一个菜单下的模板名称不能重复)
     * @param paasPrintNameEditDTO
     * @param br
     * @author xingxing.xiao
     * @date 2019/10/18 15:48
     */
    @RequestMapping(value = "/checkPrintTemplateName", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String checkPrintTemplateName(@RequestBody @Valid PaasPrintNameEditDTO paasPrintNameEditDTO, BindingResult br) {
        XbbResponse<Boolean> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                Boolean vO = paasPrintService.checkPrintTemplateName(paasPrintNameEditDTO);
                response = new XbbResponse<>(vO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取审批的业务数据
     *
     * @param paasPrintGetDataByProcessDTO
     * @param br
     * @throws
     * @return
     * @author: hongxiao
     * @date: 2020-02-11 18:09
     * @since: v4.13.0
     * @version: v4.13.0
     */
    @RequestMapping(value = "/getDataByProcess", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getDataByProcess(@RequestBody @Valid PaasPrintGetDataByProcessDTO paasPrintGetDataByProcessDTO, BindingResult br) {
        XbbResponse<JSONArray> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                JSONArray vO = paasPrintService.getDataByProcess(paasPrintGetDataByProcessDTO);
                response = new XbbResponse<>(vO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 批量获取审批的业务数据
     *
     * @param paasPrintGetDatasByProcessDTO
     * @param br
     * @throws
     * @return
     * @author: hongxiao
     * @date: 2020-02-11 18:09
     * @since: v4.13.0
     * @version: v4.13.0
     */
    @RequestMapping(value = "/getDatasByProcess", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getDatasByProcess(@RequestBody @Valid PaasPrintGetDatasByProcessDTO paasPrintGetDatasByProcessDTO, BindingResult br) {
        XbbResponse<JSONArray> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                JSONArray vO = paasPrintService.getDatasByProcess(paasPrintGetDatasByProcessDTO);
                response = new XbbResponse<>(vO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 工单支持打印
     * @param baseDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/addDefaultPrintTemplate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addDefaultPrintTemplate(@RequestBody @Valid BaseDTO baseDTO, BindingResult br) {
        XbbResponse<JSONObject> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                JSONObject integer = paasPrintService.initWorkOrderPrintTemplate(baseDTO);
                response = new XbbResponse<>(integer);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 审批打印表单筛选项
     * @param processFormFilterDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/formFilter", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formFilter(@RequestBody @Valid ProcessFormFilterDTO processFormFilterDTO, BindingResult br) {
        XbbResponse<ProcessFormFilterVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ProcessFormFilterVO processFormFilterVO = paasPrintService.formFilterForPrint(processFormFilterDTO);
                response = new XbbResponse<>(processFormFilterVO, processFormFilterVO.getList().size());
            } catch (XbbException e){
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/templateSort", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String templateSort(@RequestBody @Valid PaasPrintTemplateSortDTO paasPrintTemplateSortDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                BaseVO baseVO = paasPrintService.templateSort(paasPrintTemplateSortDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
